﻿using System.Windows;
using System.Windows.Media;

namespace Socium {
	static class UiHelper {
		/// <summary>
		/// Finds a Child of a given item in the visual tree. 
		/// </summary>
		/// <param name="parent">A direct parent of the queried item.</param>
		/// <typeparam name="T">The type of the queried item.</typeparam>
		/// <param name="child_name">x:Name or Name of child. </param>
		/// <returns>The first parent item that matches the submitted type parameter. 
		/// If not matching item can be found, 
		/// a null parent is being returned.</returns>
		public static T FindChild<T>(DependencyObject parent, string child_name)
			where T : DependencyObject {
			// Confirm parent and childName are valid. 
			if (parent == null) return null;

			T found_child = null;

			var children_count = VisualTreeHelper.GetChildrenCount(parent);
			for (var i = 0; i < children_count; i++) {
				var child = VisualTreeHelper.GetChild(parent, i);
				// If the child is not of the request child type child
				var child_type = child as T;
				if (child_type == null) {
					// recursively drill down the tree
					found_child = FindChild<T>(child, child_name);

					// If the child is found, break so we do not overwrite the found child. 
					if (found_child != null) break;
				}
				else if (!string.IsNullOrEmpty(child_name)) {
					var framework_element = child as FrameworkElement;
					// If the child's name is set for search
					if (framework_element != null && framework_element.Name == child_name) {
						// if the child's name is of the request name
						found_child = (T) child;
						break;
					}
				}
				else {
					// child element found.
					found_child = (T) child;
					break;
				}
			}

			return found_child;
		}
	}
}
